<?php
	session_start();
	include("load-settings.php");

	if(!isset($_SESSION['user']))
		header("Location: login.php");

	$user = $_SESSION['user'];

	$result = mysql_query("SELECT * FROM user WHERE id = $user");
	$row = mysql_fetch_array($result);
	$access = $row['type'];

	if($access != 2)
		header("Location: home.php");

	$result = mysql_query("SELECT * FROM payment WHERE paid = 0 ORDER BY timestamp ASC") or die(mysql_error());

	if(mysql_num_rows($result) == 0)
		header("Location: masspay.php");

	$text = "";

	while($row = mysql_fetch_array($result))
	{
		$text .= $row['paypal']."	".$row['amount']."	USD	".$row['identifier']."	".$row['booster_order']."\r\n";
		mysql_query("UPDATE payment SET paid = 1, date_paid = ".time()." WHERE id = ".$row['id']);
	}

	mysql_query("INSERT INTO mass_pay (content, timestamp) VALUES ('$text', ".time().")");

	$tmpName = tempnam(sys_get_temp_dir(), 'masspay');
	$file = fopen($tmpName, 'w');

	fwrite($file, $text);
	fclose($file);

	header('Content-Description: File Transfer');
	header('Content-Type: text/plain');
	header('Content-Disposition: attachment; filename=masspay_'.date("d_M_Y", time()).'.txt');
	header('Expires: 0');
	header('Cache-Control: must-revalidate');
	header('Pragma: public');
	header('Content-Length: ' . filesize($tmpName));

	ob_clean();
	flush();
	readfile($tmpName);

	unlink($tmpName);
?>